package org.like.sso.sso.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.like.sso.base.util.string.StringUtil;


public class SSOServiceServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 416862147654883445L;
	
	private static String className = SSOServiceServlet.class.getName();
	private static Logger logger = Logger.getLogger(className);
	

	/**
	 * Constructor of the object.
	 */
	public SSOServiceServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (null == method || "".equals(method)) {
			doNothing(request, response);
		} else if (method.equals("login")) {
			doLogin(request, response);
		} else if (method.equals("logout")) {
			doLogout(request, response);
		} else if (method.equals("getUserApplicationAccount")) {
			getUserApplicationAccount(request, response);
		} else {
			doNothing(request, response);
		}

	}

	private void doNothing(HttpServletRequest request,
			HttpServletResponse response) {

	}

	private void doLogin(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		String passWord = request.getParameter("passWord");
		String loginURL = request.getParameter("loginURL");
//		String requestPage = request.getRequestURI();
		String noLoginURL = request.getParameter("noLoginURL");

		boolean hasUser = SSOServiceUtil.checkUser(userId, passWord);
		
		
		logger.logp(Level.INFO, SSOServiceServlet.class.getName(), "doLogin", userId+"请求登录，验证hasUser为："+hasUser);

		if (hasUser) {
			// 添加到缓存中保存
			String token = request.getSession().getId() + new Date().getTime();

			boolean isOK=SSOServiceUtil.putOnLineUser(userId, token);
			if(isOK){
				response.sendRedirect(loginURL + "?Token=" + token);
			}else{
				noLoginURL=StringUtil.pickURLPar(noLoginURL, SSOConstants.REQUEST_ATTRIBUTE_MESSAGE_KEY);
				noLoginURL=noLoginURL+"="+SSOConstants.SYS_ERROR_CACHE;
				response.sendRedirect(loginURL);
			}
			
		} else {
			noLoginURL=StringUtil.pickURLPar(noLoginURL,  SSOConstants.REQUEST_ATTRIBUTE_MESSAGE_KEY);
			noLoginURL=noLoginURL+"="+SSOConstants.SYS_ERROR_DB;
			response.sendRedirect(noLoginURL);
		}

	}

	private void doLogout(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String token = request.getParameter("Token");
		boolean onLineUser = SSOServiceUtil.checkOnLineUser(token);
		
		logger.logp(Level.INFO, SSOServiceServlet.class.getName(), "doLogin", "接入系统请求登出，验证onLineUser为："+onLineUser);
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		out.println("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?>");
		out.println("<SSO>");
		out.println("<RESULT>");
		if (!onLineUser) {
			out.println("0");
			out.println("</RESULT>");
			out.println("<RESULT_MSG>");
			out.println("0");
			out.println("</RESULT_MSG>");
			out.println("<RESULT_MSGCODE>");
			out.println("USER_UNLOGIN");
		} else {
			// 如果存在，说明用户已经在线，执行登场操作则把用户信息从在线Map中删除掉
			SSOServiceUtil.delOnLineUser(token);
			out.println("1");
			out.println("</RESULT>");
			out.println("<RESULT_MSG>");
			out.println("1");
			out.println("</RESULT_MSG>");
			out.println("<RESULT_MSGCODE>");
			out.println("OK");
		}

		out.println("</RESULT_MSGCODE>");
		out.println("</SSO>");
		out.flush();
		out.close();
	}

	private void getUserApplicationAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String token = request.getParameter("Token");
		String appKey = request.getParameter(SSOConstants.SSO_APP_KEY);

		String onLineUser = SSOServiceUtil.getSubAppUserId(token, appKey);
		
		logger.logp(Level.INFO, SSOServiceServlet.class.getName(), "doLogin", "接入系统请求验证是否在线，验证onLineUser为："+onLineUser);
		// 拼接返回信息
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		out.println("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?>");
		out.println("<SSO>");
		out.println("<RESULT>");
		if (null == onLineUser || "".equals(onLineUser)) {
			out.println("1");
			out.println("</RESULT>");
			out.println("<RESULT_MSG>");
			out.println("0");
			out.println("</RESULT_MSG>");
			out.println("<RESULT_MSGCODE>");
			out.println("USER_UNLOGIN");
			out.println("</RESULT_MSGCODE>");
			out.println("<ACCOUNT>");
			out.println("");
		} else {
			out.println("1");
			out.println("</RESULT>");
			out.println("<RESULT_MSG>");
			out.println("1");
			out.println("</RESULT_MSG>");
			out.println("<RESULT_MSGCODE>");
			out.println("OK");
			out.println("</RESULT_MSGCODE>");
			out.println("<ACCOUNT>");
			out.println(onLineUser);
		}

		out.println("</ACCOUNT>");
		out.println("</SSO>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * 
	 * 取得真实的客户端访问ip。
	 * 
	 * @param request
	 * @return
	 */
	public String getRealIpAddres(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;

	}
	
	

}
